package com.system.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.user.mapper.AdminMapper;
import com.system.common.bean.Admin;
import com.system.common.exception.ServiceException;
import com.system.common.service.IAdminService;
import org.apache.dubbo.config.annotation.DubboService;


import java.util.List;

@DubboService
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Override
    public Admin getAdminById(Integer id) {
        return super.getById(id);
    }

    @Override
    public Admin getAdminByUsername(String username) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, username);
        return super.getOne(queryWrapper);
    }

    @Override
    public void addAdmin(Admin admin) {
        super.save(admin);
    }

    @Override
    public void updateAdmin(Admin admin) {
        super.updateById(admin);
    }

    @Override
    public void deleteAdmin(Integer id) {
        Admin admin = super.getById(id);
        if (admin == null) {
            throw new ServiceException("管理员不存在");
        }
        if(admin.getIsdel()==1){
            throw new ServiceException("管理员已删除");
        }
        super.removeById(id);
    }

    @Override
    public void updateStatus(Integer id, Integer status) {
        Admin admin = super.getById(id);
        // 若管理员不存在，可抛出业务异常或直接返回（根据你的业务逻辑选择）
        if (admin == null) {
            throw new ServiceException("管理员不存在"); // 建议自定义业务异常
        }
        admin.setStatus(status);
        super.updateById(admin);
    }

    @Override
    public List<Admin> getAdminList() {
        return super.list();
    }


    @Override
    public Page<Admin> getPage(Admin admin, Page<Admin> page) {
        // 构建查询条件
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        if (admin.getUsername() != null && !admin.getUsername().isEmpty()) {
            queryWrapper.like(Admin::getUsername, admin.getUsername());
        }

        // 执行分页查询
        Page<Admin> resultPage = baseMapper.selectPage(page, queryWrapper);

        Long total = this.count(queryWrapper);
        resultPage.setTotal(total);

        return resultPage;
    }
}
